package com.example.network.service.impl;

import com.example.network.controller.dto.EmailDTO;
import com.example.network.exception.ServiceException;
import com.example.network.mapper.UserMapper;
import com.example.network.service.EmailService;
import jakarta.annotation.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Service("emailService")
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender mailSender;
    @Resource
    private UserMapper userMapper;

    /**
     * 生成验证码
     * @param length
     * @return
     */
    private String generateVerificationCode(int length) {
        // 创建一个StringBuilder对象，用于构建验证码字符串
        StringBuilder code = new StringBuilder();
        // 创建一个Random对象，用于生成随机数
        Random random = new Random();
        // 循环指定长度次数，每次生成一个随机数并添加到验证码字符串中
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        // 返回生成的验证码字符串
        return code.toString();
    }

    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @Override
    public void sendCode(String email) {
        if (email==null){
            throw new ServiceException("请输入邮箱地址进行注册");
        }
        EmailDTO emailDTO = userMapper.selectEmailCode(email);
        if (emailDTO==null){
            userMapper.insertEmail(email,null,0);
        }
        // 创建一个SimpleMailMessage对象，用于构建邮件内容
        SimpleMailMessage message = new SimpleMailMessage();
        // 设置邮件接收者
        message.setTo(email);
        // 设置邮件主题
        message.setSubject("账户密码修改验证");
        // 设置邮件正文内容，包含验证码
        String verificationCode = generateVerificationCode(6);
        message.setText("您的验证码是: " + verificationCode+"。验证码有效期为30分钟，为了您的账户安全，请勿将该验证码透露给其他人。"
                        +"\n"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年 MM月 dd日 HH:mm")));
        // 设置邮件发送者
        message.setFrom("gll3@qq.com");
        // 使用JavaMailSender发送邮件
        mailSender.send(message);
        userMapper.updateEmailCode(email,verificationCode,System.currentTimeMillis()+30*60*1000);
    }
}
